package com.xiaojie.persistence.core.builder;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import com.xiaojie.persistence.core.Resources;
import com.xiaojie.persistence.core.entity.Configuration;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author 小杰
 * @date 2021/5/5
 * @description 根据XML文件解析配置文件的构造类
 */
public class XMLConfigBuilder {

    private Configuration configuration;

    public XMLConfigBuilder() {
        this.configuration = new Configuration();
    }


    public Configuration parseConfig(InputStream inputStream) throws DocumentException, PropertyVetoException, ClassNotFoundException {

        Document document = new SAXReader().read(inputStream);

        // 根节点 <configuration>
        Element rootElement = document.getRootElement();
        List<Element> dataSourceElements = rootElement.selectNodes("//dataSource");
        // 拿到数据源的数据,默认至少有一个,取一个
        Element dataSourceElement = dataSourceElements.get(0);
        List<Element> propertyElements = dataSourceElement.selectNodes("//property");
        // 下面遍历设置数据源信息
        Properties properties = new Properties();
        for(Element propertyElement : propertyElements) {
            String name = propertyElement.attributeValue("name");
            String value = propertyElement.attributeValue("value");
            properties.setProperty(name, value);
        }

        // 创建数据源
        ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
        comboPooledDataSource.setDriverClass(properties.getProperty("driverClass"));
        comboPooledDataSource.setJdbcUrl(properties.getProperty("jdbcUrl"));
        comboPooledDataSource.setUser(properties.getProperty("username"));
        comboPooledDataSource.setPassword(properties.getProperty("password"));
        configuration.setDataSource(comboPooledDataSource);


        // 解析Mapper
        List<Element> mapperElements = rootElement.selectNodes("//mapper");
        for (Element element : mapperElements) {
            String mapperPath = element.attributeValue("resource");
            InputStream resourceAsSteam = Resources.getResourceAsStream(mapperPath);
            XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(configuration);
            xmlMapperBuilder.parse(resourceAsSteam);
        }

        return configuration;
    }

}
